package com.bk.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hashids.Hashids;
import org.joda.time.DateTime;

import com.cjw.model.DBMap;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.moomi.common.model.BkBooking;
import com.moomi.common.model.BkItem;
import com.moomi.common.model.BkItemSelection;
import com.moomi.common.model.BkSelection;
import com.moomi.common.model.BkSelectionOff;
import com.moomi.common.model.BkShop;
import com.moomi.common.model.BkUser;
import com.utils.AuthUtils;
import com.utils.DateUtils;
import com.utils.PathUtils;
import com.utils.QNUtils;
import com.utils.image.UploadUtils;
import com.utils.interceptor.TestInterceptor;
import com.zhenyi.core.VueUtils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;

public class BKAdminController extends BKController {
	private final int PAGE_SIZE = 50;

	@Clear
	public void login() {
		String userName = getPara("userName");
		String password = getPara("password");
		if (StrKit.isBlank(userName) || StrKit.isBlank(password)) {
			renderFailure();
			return;
		}
		try {
			DBMap map = new DBMap();
			map.put("email", userName);
			map.put("password", password);
			BkUser user = BkUser.dao.searchFirst(map);
			if (user != null) {
				String token = AuthUtils.login(user.getId() + "", this);
				renderSuccess(token);
				return;
			}
		} catch (Exception e) {
			LogKit.error("login fail", e);
		}
		renderFailure(500, "账号/密码错误");
	}

	public void logout() {
		renderFlag(AuthUtils.logout(this));
	}

	public void upload() {
		try {
			File file = getFileParam("file");
			if (UPLOAD_MODE == 1) {
				String key = getPara("key");
				if (key == null) {
					key = StrKit.getRandomUUID();
				}
				key = "temp/" + key;
				QNUtils utils = new QNUtils("JrRlQ9yhAxFonToRC_hOfqJ8VBvy786T2TQGn7D8",
						"rXztWGzgrRilAyJysgdvxJFgPs63DGTZta1g6YcI", "resource", "http://res.zhen-yee.com", false);
				utils.project = "tmp/";
				String url = utils.upload(file, key);
				renderResult(url);
			} else if (UPLOAD_MODE == 2) {
				String url = UploadUtils.upload(file);
				renderResult(url);
			}
		} catch (Exception e) {
			LogKit.error("upload fail", e);
			renderFailure(500, "服务器给你搞爆了");
		}
	}

	/**
	 * 项目
	 */
	public void items() {
		BkUser user = getUser();
		long shopId = user.getSelectedShop();
		SqlPara sqlPara = Db.getSqlPara("FindItems", shopId);
		Page<BkItem> pages = BkItem.dao.paginate(getPage(), PAGE_SIZE, sqlPara);
		renderPage(pages);
	}

	public void itemInfo() {
		Integer itemId = getParaToInt("itemId");
		BkItem item = BkItem.dao.findById(itemId);
		renderResult(item);
	}

	public void itemSelection() {
		BkUser user = getUser();
		int shopId = user.getSelectedShop();
		Integer itemId = getParaToInt("itemId");
		SqlPara sqlPara = Db.getSqlPara("FindSelections", shopId);
		List<BkSelection> items = BkSelection.dao.find(sqlPara);
		if (itemId != null) {
			SqlPara sql = Db.getSqlPara("FindItemSelections", itemId);
			List<BkSelection> selections = BkSelection.dao.find(sql);
			for (BkSelection item : items) {
				for (BkSelection selection : selections) {
					if (selection.getId().equals(item.getId())) {
						item.put("enable", true);
						break;
					} else {
						item.put("enable", false);
					}
				}
			}
		}
		renderResult(items);
	}

	public void itemSubmit() {
		Long id = getParaToLong("id");
		BkUser user = getUser();
		Integer shopId = user.getSelectedShop();
		String name = getPara("name");
		String image = getPara("image");
		Integer price = getParaToInt("price");
		String date = getPara("date");
		String intro = getPara("intro");
		float spend = getParaToInt("spend");

		BkItem bkItem;
		if (id == null) {
			bkItem = new BkItem();
		} else {
			bkItem = BkItem.dao.findById(id);
		}
		bkItem.setName(name);
		bkItem.setPrice(price);
		bkItem.setImage(image);
		bkItem.setDate(date);
		bkItem.setSpend(spend);
		bkItem.setIntro(intro);
		bkItem.setShopId(shopId);
		boolean flag = bkItem.updateIfExist();
		renderFlag(flag);
	}

	public void itemSelectionSubmit() {
		Integer itemId = getParaToInt("itemId");
		String selectionIds = getPara("selectionIds");
		String[] selectionIdArray = selectionIds.split(";");

		SqlPara sql = Db.getSqlPara("ItemSelections", itemId);
		List<BkItemSelection> items = BkItemSelection.dao.find(sql);
		for (BkItemSelection item : items) {
			item.delete();
		}
		for (String selectionIdStr : selectionIdArray) {
			Integer selectionId = Integer.parseInt(selectionIdStr);
			BkItemSelection bkItemSelection = new BkItemSelection();
			bkItemSelection.setItemId(itemId);
			bkItemSelection.setSelectionId(selectionId);
			bkItemSelection.save();
		}
		renderSuccess();
	}

	public void itemDelete() {
		Integer itemId = getParaToInt("itemId");
		BkItem bkItem = BkItem.dao.findById(itemId);
		boolean flag = bkItem.delete();
		renderFlag(flag);
	}

	/**
	 * 技师
	 */
	public void selections() {
		BkUser user = getUser();
		int shopId = user.getSelectedShop();
		SqlPara sqlPara = Db.getSqlPara("FindSelections", shopId);
		Page<BkSelection> pages = BkSelection.dao.paginate(getPage(), PAGE_SIZE, sqlPara);
		renderPage(pages);
	}

	public void online() {
		Integer selectionId = getParaToInt("selectionId");
		BkSelection selection = BkSelection.dao.findById(selectionId);
		if (selection.getOnline() == 0) {
			selection.setOnline(1);
		} else {
			selection.setOnline(0);
		}
		Boolean flag = selection.update();
		renderFlag(flag);
	}

	public void selectionInfo() {
		Integer selectionId = getParaToInt("selectionId");
		BkSelection selection = BkSelection.dao.findById(selectionId);
		renderResult(selection);
	}

	public void selectionsSubmit() {
		BkUser user = getUser();
		int shopId = user.getSelectedShop();
		Integer selectionId = getParaToInt("selectionId");
		String name = getPara("name");
		String image = getPara("image");
		String intro = getPara("intro");
		String email = getPara("email");
		BkSelection selection;
		if (selectionId == null) {
			selection = new BkSelection();
		} else {
			selection = BkSelection.dao.findById(selectionId);
		}
		selection.setName(name);
		selection.setImage(image);
		selection.setIntro(intro);
		selection.setEmail(email);
		selection.setShopId(shopId);
		Boolean flag = selection.updateIfExist();
		renderFlag(flag);
	}

	public void selectionDelete() {
		Integer selectionId = getParaToInt("selectionId");
		BkSelection selection = BkSelection.dao.findById(selectionId);
		Boolean flag = selection.delete();
		renderFlag(flag);
	}

	/**
	 * 订单
	 */
	public void booking() {
		BkUser user = getUser();
		int shopId = user.getSelectedShop();
		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		SqlPara sqlPara = Db.getSqlPara("FindBookings", shopId, startDate, endDate);
		Page<BkSelection> pages = BkSelection.dao.paginate(getPage(), PAGE_SIZE, sqlPara);
		renderPage(pages);
	}

	public void cancel() {
		Integer bookingId = getParaToInt("bookingId");
		BkBooking booking = BkBooking.dao.findById(bookingId);
		booking.setStatus(-1);
		Boolean flag = booking.update();
		renderFlag(flag);
	}

	public void arrive() {
		Integer bookingId = getParaToInt("bookingId");
		BkBooking booking = BkBooking.dao.findById(bookingId);
		booking.setIsArrive(1);
		Boolean flag = booking.update();
		renderFlag(flag);
	}

	public void shop() {
		BkUser user = getUser();
		int shopId = user.getSelectedShop();
		BkShop shop = BkShop.dao.findById(shopId);
		renderResult(shop);
	}

	public void shopSubmit() {
		BkUser user = getUser();
		int shopId = user.getSelectedShop();
		String name = getPara("name");
		String address = getPara("address");
		String phone = getPara("phone");
		String intro = getPara("intro");
		String logo = getPara("logo");
		String openStr = getPara("openStr");
		String closeStr = getPara("closeStr");
		BkShop shop = BkShop.dao.findById(shopId);
		shop.setName(name);
		shop.setAddress(address);
		shop.setPhone(phone);
		shop.setIntro(intro);
		shop.setLogo(logo);
		shop.setOpenStr(openStr);
		shop.setCloseStr(closeStr);
		Boolean flag = shop.update();
		renderFlag(flag);
	}

	public void shops() {
		BkUser user = getUser();
		SqlPara sqlPara = Db.getSqlPara("BKShops", user.getId());
		List<BkShop> shops = BkShop.dao.find(sqlPara);
		renderResult(shops);
	}

	public void myShop() {
		BkUser user = getUser();
		Integer shopId = user.getSelectedShop();
		BkShop shop = BkShop.dao.findById(shopId);
		renderResult(shop);
	}

	public void swithShop() {
		Integer shopId = getParaToInt("shopId");
		setShopId(shopId);
		int newShopId = getShopId();
		BkUser user = getUser();
		user.setSelectedShop(newShopId);
		Boolean flag = user.update();
		renderFlag(flag);
	}

	public void dayoffs() {
		BkUser user = getUser();
		long shopId = user.getSelectedShop();
		SqlPara sqlPara = Db.getSqlPara("Dayoffs", shopId);
		Page<BkSelectionOff> pages = BkSelectionOff.dao.paginate(getPage(), PAGE_SIZE, sqlPara);
		renderPage(pages);
	}

	public void dayoffSelection() {
		BkUser user = getUser();
		long shopId = user.getSelectedShop();
		SqlPara sqlPara = Db.getSqlPara("FindSelections", shopId);
		List<BkSelection> selections = BkSelection.dao.find(sqlPara);
		SqlPara dayoffSqlPara = Db.getSqlPara("dayoffSelections", shopId);
		List<BkSelection> dayoffSelections = BkSelection.dao.find(dayoffSqlPara);
		for (BkSelection selection : selections) {
			for (BkSelection dayoffSelection : dayoffSelections) {
				if (selection.getId().equals(dayoffSelection.getId())) {
					selection.put("isDayoff", true);
					break;
				} else {
					selection.put("isDayoff", false);
				}
			}
		}
		renderResult(selections);
	}

	public void submitDayoff() {
		long selectionId = getParaToInt("selectionId");
		String startDateStr = getPara("startDate");
		String endDateStr = getPara("endDate");
		Date startDate = DateUtils.dateFromString(startDateStr);
		Date endDate = DateUtils.dateFromString(endDateStr);
		Date addDate = new Date();
		BkSelectionOff selectionOff = new BkSelectionOff();
		selectionOff.setSelectionId(selectionId);
		selectionOff.setStartDate(startDate);
		selectionOff.setEndDate(endDate);
		selectionOff.setAddDate(addDate);
		Boolean flag = selectionOff.save();
		renderFlag(flag);
	}

	public void deleteDayoff() {
		Integer id = getParaToInt("id");
		BkSelectionOff selectionOff = BkSelectionOff.dao.findById(id);
		Boolean flag = selectionOff.delete();
		renderFlag(flag);
	}

	private String shortUrl(String url, String keyword) {
		keyword = "";
		String urlString = "https://u.nu/api.php?action=shorturl&format=simple&url=" + url + "&keyword=" + keyword;
		return HttpUtil.get(urlString);
	}

	@Clear
	public void hhh() {
		String salt = getPara(0);
		Integer len = getParaToInt(1);
		Hashids hashids = new Hashids(salt, len);
		String value = hashids.encode(1000);
		renderText(value);
	}

	@Clear
	public void cancelMobile() {
		Integer bookingId = getParaToInt("bookingId");
		BkBooking booking = BkBooking.dao.findById(bookingId);
		booking.setStatus(-1);
		Boolean flag = booking.update();
		renderFlag(flag);
	}

	@Clear
	@Before(TestInterceptor.class)
	public void gen() {
		Integer shopId = getParaToInt(0);
		BkShop shop = BkShop.dao.findById(shopId);
		Hashids hashids = new Hashids("zhenyuding", 6);
		String encodeShopId = hashids.encode(shopId);
		String url = "http://booking.zhen-yee.com/admin/todayBooking/?shopId={}";
		url = StrFormatter.format(url, encodeShopId);
		String shortUrl = shortUrl(url, encodeShopId);

		String qrcodeUrl = "http://qr.liantu.com/api.php?text={}&logo={}";
		String encodetUrl = URLUtil.encode(shortUrl);
		String logoUrl = "http://res.zhen-yee.com/zy/logo50.jpg";
		logoUrl = URLUtil.encode(logoUrl);

		qrcodeUrl = StrFormatter.format(qrcodeUrl, encodetUrl, logoUrl);
		String fileName = shop.getName() + "-" + shopId + ".png";
		File file = new File(PathUtils.getFile("image", fileName));
		if (!file.exists()) {
			Long size = HttpUtil.downloadFile(qrcodeUrl, file);
			if (size == 0) {
				LogKit.error("fail ");
			}
		}
		String html = "<img src='{}'/><a target='_blank' href='{}'>{}</a>";
		html = StrFormatter.format(html, "/image/" + fileName, shortUrl, shop.getName());
		// String html = HttpUtil.get("http://qr.liantu.com/api.php?text=" +
		// shortUrl);
		// System.out.println(html);
		// // redirect("http://qr.liantu.com/api.php?text=" + shortUrl);
		renderHtml(html);
	}

	@Clear
	public void updateBookingInfo() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure();
			return;
		}
		BkBooking booking = BkBooking.dao.findById(id);
		if (booking == null) {
			renderFailure();
			return;
		}
		String remark = getPara("remark");
		if (StrKit.notBlank(remark)) {
			booking.setRemark(remark);
			booking.update();
		}
		renderSuccess();
	}

	@Clear
	public void todayBooking() {
		try {
			ArrayList<String> dates = new ArrayList<>();
			String selectDay = getPara("selectDay");
			if (selectDay == null) {
				selectDay = DateUtils.dateFormat(new Date(), DateUtils.YYYYMMDD);
			} else {
				Date submitDate = DateUtils.dateFromString(selectDay, DateUtils.YYYYMMDD);
				if (submitDate.getTime() <= new Date().getTime()) {
					selectDay = DateUtils.dateFormat(new Date(), DateUtils.YYYYMMDD);
				}
			}
			DateTime date = new DateTime();
			for (int i = 0; i < 30; i++) {
				Date newDate = date.plusDays(i).toDate();
				dates.add(DateUtil.format(newDate, DateUtils.YYYYMMDD));
			}
			String shopCode = getPara("shopId");
			if (shopCode == null) {
				redirect("http://booking.zhen-yee.com");
				return;
			}
			Hashids hashids = new Hashids("zhenyuding", 6);
			Long shopId = hashids.decode(shopCode)[0];
			BkShop shop = BkShop.dao.findById(shopId);
			String title = shop.getName() + "预约";
			SqlPara sqlPara = Db.getSqlPara("todayBookings", shopId, selectDay);
			List<BkBooking> items = BkBooking.dao.find(sqlPara);
			setAttr("title", title);
			setAttr("items", items);
			setAttr("data", VueUtils.getVueData(items));
			setAttr("dates", dates);
			setAttr("shopId", shopCode);
			setAttr("selectDay", selectDay);
			render("/bk/booking/todayBooking.html");
		} catch (Exception e) {
			LogKit.error("todayBooking error", e);
			renderText("");
		}
	}

	@Clear
	public void index() {
		render("/bk/admin/index.html");
	}
}
